package seata.demo.account.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import seata.demo.account.entity.TAccount;
import seata.demo.account.mappers.TAccountMapper;
import seata.demo.common.dto.AccountDTO;
import seata.demo.common.enums.RspStatusEnum;
import seata.demo.common.response.ObjectResponse;

@RestController
@RequestMapping("/account")
@Slf4j
public class AccountServiceImpl extends ServiceImpl<TAccountMapper, TAccount> {

    @PostMapping("/decreaseAccount")
    @GlobalTransactional
    @Transactional
    public ObjectResponse decreaseAccount(@RequestBody AccountDTO accountDTO) {

        log.info("seata全局xid={}", RootContext.getXID());

        int account = baseMapper.decreaseAccount(accountDTO.getUserId(), accountDTO.getAmount().doubleValue());
        ObjectResponse<Object> response = new ObjectResponse<>();
        if (account > 0) {
            response.setStatus(RspStatusEnum.SUCCESS.getCode());
            response.setMessage(RspStatusEnum.SUCCESS.getMessage());
            return response;
        }

        response.setStatus(RspStatusEnum.FAIL.getCode());
        response.setMessage(RspStatusEnum.FAIL.getMessage());
        return response;
    }
}
